package com.xyzq.cgate.admin;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.xyzq.cgate.admin.bootstrap.Bootstrap;
import com.xyzq.cgate.common.enums.PluginDetailEnum;
import com.xyzq.cgate.common.exception.CgateException;
import com.xyzq.cgate.common.rule.custom.entity.RequestData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/17 10:52
 */
@Component
public class CgateAdminApplicationRunnner implements ApplicationRunner {

    @Autowired
    CgateAdminApplicationListener cgateAdminApplicationListener;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        int serverPort = cgateAdminApplicationListener.getServerPort();
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        if(!new Bootstrap().bootstrapSyncPlugin(hostAddress, serverPort)) {
            throw new CgateException("plugin sync error");
        }

        List<String> ruleList = Lists.newArrayList();
        Arrays.stream(PluginDetailEnum.values()).forEach(
            p -> ruleList.add(p.getName())
        );
        if(!new Bootstrap().bootstrapSyncRule(hostAddress, serverPort,
                new RequestData(Joiner.on(",").skipNulls().join(ruleList)))) {
            throw new CgateException("rule sync error");
        }

    }
}
